/**
 * date:2020/02/27
 * author:Mr.Chung
 * version:2.0
 * description:layuimini 菜单框架扩展
 */
layui.define(['element', 'laytpl'], function (exports) {
    const element = layui.element,
          $ = layui.$,
          laytpl = layui.laytpl,
          layer = layui.layer;
    const MENU_ITEM_TPL =
        `<li {{# if(d.menu){ }} data-menu="{{- d.menu }}" {{# } }}
                class="layui-nav-item {{- d.childOpenClass ? d.childOpenClass : '' }} {{- d.className ? d.className : '' }}"
                {{# if(d.id){ }} id="{{- d.id }}" {{# } }}>
            <a {{# if(d.href){ }} layuimini-href="{{- d.href }}" {{# } }}
                    {{# if(d.target){ }} target="{{- d.target }}" {{# } }}
                    href="javascript:;">
                {{# if(d.icon){ }} <i class="{{- d.icon }}"></i> {{# } }}
                <span class="layui-left-nav">{{- d.title }}</span>
            </a>
            {{# if(d.children){ }} {{- d.children }} {{# } }}
        </li>`;
    const CHILD_MENU_ITEM_TPL =
        `<dd class="{{- d.childOpenClass ? d.childOpenClass : '' }} {{- d.className ? d.className : '' }}">
            <a href="javascript:;"
                    {{# if(d.menu){ }} data-menu="{{- d.menu }}" {{# } }}
                    {{# if(d.id){ }} id="{{- d.id }}" {{# } }}
                    {{# if((!d.child || !d.child.length) && d.href){ }} layuimini-href="{{- d.href }}" {{# } }}
                    {{# if(d.target){ }} target="{{- d.target }}" {{# } }}>
                {{# if(d.icon){ }} <i class="{{- d.icon }}"></i> {{# } }}
                <span class="layui-left-nav">{{- d.title }}</span>
            </a>
            {{# if(d.children){ }} {{- d.children }} {{# } }}
        </dd>`;
    const MENU_CONTAINER_TPL =
        `<ul class="layui-nav layui-nav-tree layui-left-nav-tree {{- d.className }}"
                id="{{- d.id }}">
            {{- d.children }}
        </ul>`;
    const CHILD_MENU_CONTAINER_TPL = `<dl class="layui-nav-child">{{- d.children }}</dl>`;

    let headerMenuIdSelected = '';
    // 缓存菜单数据
    let menuData = [];

    const miniMenu = {

        /**
         * 菜单初始化
         * @param options.menuList   菜单数据信息
         * @param options.multiModule 是否开启多模块
         * @param options.menuChildOpen 是否展开子菜单
         */
        render: function (options) {
            options.menuList = options.menuList || [];
            options.multiModule = options.multiModule || false;
            options.menuChildOpen = options.menuChildOpen || false;
            if (options.multiModule) {
                miniMenu.renderMultiModule(options.menuList, options.menuChildOpen);
            } else {
                miniMenu.renderSingleModule(options.menuList, options.menuChildOpen);
            }
            miniMenu.listen();
        },
        each: function (list, callback) {
            const _list = [];
            for (let i = 0, len = list.length; i < len; ++i) {
                _list[i] = callback(i, list[i]);
            }
            return _list;
        },
        /**
         * 封装菜单外壳
         *
         * @param menu 数据
         * @param isSub 是否为子菜单
         * @returns string
         */
        packageMenuContainer: function (menu, isSub) {
            // 没有要封装的内容，直接返回
            if (!menu.children) {
                return '';
            }
            return laytpl(isSub ? CHILD_MENU_CONTAINER_TPL : MENU_CONTAINER_TPL).render(menu);
        },
        /**
         * 生成菜单项的HTML
         *
         * @param menu 菜单数据
         * @param isSub 是否为子菜单项
         * @returns string
         */
        generateMenuItemHtml: function (menu, isSub) {
            return laytpl(isSub ? CHILD_MENU_ITEM_TPL : MENU_ITEM_TPL).render(menu);
        },

        /**
         * 生成子菜单HTML
         *
         * @param menuList 子菜单数据
         * @param options 选项数据
         * @returns {string}
         */
        generateChildrenMenuHtml: function (menuList, options) {
            menuList = menuList || [];
            const html = this.each(menuList, function (idx, menu) {
                if (menu.child && menu.child.length) {
                    menu.children = miniMenu.generateChildrenMenuHtml(menu.child, {childOpenClass: options.childOpenClass || ''});
                }
                menu.className = '';
                menu.childOpenClass = options.childOpenClass || '';
                return miniMenu.generateMenuItemHtml(menu, true);
            }).join('');
            return miniMenu.packageMenuContainer({children: html}, true)
        },
        /**
         * 生成左侧菜单
         *
         * @param leftMenus 左侧菜单数据
         * @param options 选项数据
         * @returns {string}
         */
        generateLeftMenu: function (leftMenus, options) {
            options = options || {};
            let leftMenusHtml = miniMenu.each(leftMenus || [], function (idx, leftMenu) { // 左侧菜单遍历
                const children = miniMenu.generateChildrenMenuHtml(leftMenu.child, {childOpenClass: options.childOpenClass});
                return miniMenu.generateMenuItemHtml({
                    href: leftMenu.href,
                    target: leftMenu.target,
                    childOpenClass: options.childOpenClass,
                    icon: leftMenu.icon,
                    title: leftMenu.title,
                    children: children
                }, false);
            }).join('');

            leftMenusHtml = miniMenu.packageMenuContainer({
                id: options.parentMenuId,
                className: options.leftMenuCheckDefault,
                children: leftMenusHtml
            }, false);
            return leftMenusHtml;
        },
        /**
         * 多模块
         *
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderMultiModule: function (menuList, menuChildOpen) {
            if (!menuList || menuList.length < 1) {
                return;
            }

            let headerMenuHtml = '',
                headerMobileMenuHtml = '',
                leftMenuHtml = '',
                leftMenuCheckDefault = 'layui-this',
                childOpenClass = '',
                headerMenuCheckDefault = 'layui-this',
                // 默认渲染第一个菜单
                defaultMenuIndex = 0,
                defaultMenuId = 'multi_module_' + defaultMenuIndex;

            if (menuChildOpen) childOpenClass = ' layui-nav-itemed';

            // 缓存菜单数据
            menuData = menuList;
            // 默认给第1个菜单
            if (!headerMenuIdSelected) headerMenuIdSelected = defaultMenuId;

            // 渲染头部菜单
            headerMenuHtml = this.each(menuList, function (index, val) { //顶部菜单渲染
                const menu = 'multi_module_' + index;
                const id = menu + 'HeaderId';
                let topMenuItemHtml = '';
                // 默认给第1个菜单
                if (!headerMenuIdSelected) headerMenuIdSelected = menu;
                topMenuItemHtml = miniMenu.generateMenuItemHtml({
                    className: headerMenuCheckDefault,
                    menu: menu,
                    id: id,
                    title: val.title,
                    href: '',
                    target: '',
                    children: ''
                }, false);
                // leftMenuHtml += miniMenu.generateLeftMenu(val.child, {
                //     parentMenuId: menu,
                //     childOpenClass: childOpenClass,
                //     leftMenuCheckDefault: leftMenuCheckDefault
                // });
                headerMobileMenuHtml += miniMenu.generateMenuItemHtml({
                    id: id,
                    menu: menu,
                    icon: val.icon,
                    title: val.title,
                }, true);
                headerMenuCheckDefault = '';
                // leftMenuCheckDefault = "layui-hide";
                return topMenuItemHtml;
            }).join('');


            // 渲染左侧菜单
            leftMenuHtml = miniMenu.generateLeftMenu(menuList[defaultMenuIndex].child, {
                parentMenuId: defaultMenuId,
                childOpenClass: childOpenClass,
                leftMenuCheckDefault: leftMenuCheckDefault
            });

            $('.layui-layout-body').addClass('layuimini-multi-module'); //多模块标识
            $('.layuimini-menu-header-pc').html(headerMenuHtml); //电脑
            $('.layuimini-menu-left').html(leftMenuHtml);
            $('.layuimini-menu-header-mobile').html(headerMobileMenuHtml); //手机
            element.init();
        },
        /**
         * 单模块
         * @param menuList 菜单数据
         * @param menuChildOpen 是否默认展开
         */
        renderSingleModule: function (menuList, menuChildOpen) {
            menuList = menuList || [];
            let leftMenuHtml = '',
                childOpenClass = '',
                leftMenuCheckDefault = 'layui-this';
            if (menuChildOpen) childOpenClass = ' layui-nav-itemed';
            leftMenuHtml = this.generateLeftMenu(menuList, {childOpenClass: childOpenClass});
            $('.layui-layout-body').addClass('layuimini-single-module'); //单模块标识
            $('.layuimini-header-menu').remove();
            $('.layuimini-menu-left').html(leftMenuHtml);

            element.init();
        },
        /**
         * 重新加载左侧菜单
         * @param menuId 左侧菜单ID
         */
        reloadLeftMenu: function (menuId) {
            console.log('id =>', menuId);
            // 防止重复点击
            if (menuId === headerMenuIdSelected) {
                return;
            }

            const loading = layer.load(0, {shade: false, time: 2 * 1000});

            // 更新选中
            headerMenuIdSelected = menuId;

            // 动态渲染菜单
            let index = Number(menuId.substring(menuId.lastIndexOf('_') + 1));
            if (menuData.length <= index || index < 0) {
                console.error('未知的菜单id:', menuId);
                return;
            }
            let leftMenuHtml = miniMenu.generateLeftMenu(menuData[index].child, {
                parentMenuId: menuId,
                childOpenClass: '',
                leftMenuCheckDefault: ''
            });
            $(".layuimini-menu-left").html(leftMenuHtml);
            element.render('nav');

            layer.close(loading);
        },
        /**
         * 监听
         */
        listen: function () {
            /**
             * 绑定头部菜单点击事件
             */
            element.on('nav(jp-header-menu)', function(elem) {
                const menuId = elem.parent().attr('data-menu');
                miniMenu.reloadLeftMenu(menuId);
            });
            /**
             * 绑定移动端菜单点击事件
             */
            element.on('nav(jp-header-menu-mobile)', function (elem) {
                const menuId = elem.attr('data-menu');
                if (!menuId) return;
                miniMenu.reloadLeftMenu(menuId);
            });

            /**
             * 菜单缩放
             */
            $('body').on('click', '.layuimini-site-mobile', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
            });
            /**
             * 菜单缩放
             */
            $('body').on('click', '[data-side-fold]', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var isShow = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (isShow == 1) { // 缩放
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 0);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-indent');
                    $('.layui-layout-body').removeClass('layuimini-all');
                    $('.layui-layout-body').addClass('layuimini-mini');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).addClass("hidden-sub-menu");
                    // });

                } else { // 正常
                    $('.layuimini-tool [data-side-fold]').attr('data-side-fold', 1);
                    $('.layuimini-tool [data-side-fold]').attr('class', 'fa fa-outdent');
                    $('.layui-layout-body').removeClass('layuimini-mini');
                    $('.layui-layout-body').addClass('layuimini-all');
                    // $(".menu-li").each(function (idx,el) {
                    //     $(el).removeClass("hidden-sub-menu");
                    // });
                    layer.close(window.openTips);
                }
                element.init();
                layer.close(loading);
            });

            /**
             * 手机端点开模块
             */
            $('body').on('click', '.layuimini-header-menu.layuimini-mobile-show dd', function () {
                var loading = layer.load(0, {shade: false, time: 2 * 1000});
                var check = $('.layuimini-tool [data-side-fold]').attr('data-side-fold');
                if (check === "1") {
                    $('.layuimini-site-mobile').trigger("click");
                    element.init();
                }
                layer.close(loading);
            });
        },

    };


    exports("miniMenu", miniMenu);
});
